from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.paginator import Paginator
from .ser import *
from utils.comm import send_message
import random
from utils.comm import get_redis
from meiduo import settings


# Create your views here.


class Test(APIView):
    def get(self, request):
        # print(send_message('15237332931', '123456', '1'))
        # return Response('ok')
        # conn = redis.Redis(host='localhost', port=6379, decode_responses=True)

        conn = get_redis()
        conn.setex('name', 5, 'qwe')
        name = conn.get('name')
        return Response(name)


class NewsM(APIView):
    def post(self, request):
        ser = NewsSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        cpage = request.GET.get('cpage')
        news = News.objects.all()
        p = Paginator(news, 2)
        newss = p.page(cpage)
        ser = NewsSer(newss, many=True)
        return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


class XWM(APIView):
    def post(self, request):
        ser = XWser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        cpage = request.GET.get('cpage')
        xinw = Advertisement.objects.all()
        p = Paginator(xinw, 2)
        xinws = p.page(cpage)
        ser = XWser(xinws, many=True)
        return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


import re
from django.contrib.auth.hashers import check_password, make_password


class RegiM(APIView):
    def post(self, request):
        username = request.data.get('username')
        # 1是否为空
        if not username:
            return Response({'code': 20010})
        # 2是否符合
        name = re.match('\w{5,10}$', username)
        print(name)
        if not name:
            return Response({'code': 20011})
        # 3是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 20012})
            # 密码
        password = request.data.get('password')
        if not password:
            return Response({'code': 10010})
        password = re.match('\w{8,20}$', password)
        if not password:
            return Response({'code': 10011})

        # 手机号
        mobile = request.data.get('mobile')
        # 1是否为空
        if not mobile:
            return Response({'code': 20013})
        # 2是否符合
        num = re.match('^1[3-9]\d{9}$', mobile)
        if not num:
            return Response({'code': 20014})

        codes = request.data.get('codes')
        conn = get_redis()
        codess = conn.get(mobile)
        if codess:
            codess = str(codess, encoding='utf8')
        #
        if codes != codess:
            return Response({'code': 10016})
        #     request.data['password'] = make_password(request.data.get('password'))
        #     is_check = request.data.get('is_check')
        #     if is_check:
        #         ser = Userser(data=request.data)
        #         if ser.is_valid():
        #             ser.save()
        #         else:
        #             print(ser.errors)
        #             return Response({'code': 10016})

        return Response({'code': 200})


import jwt


class RegiM2(APIView):
    def post(self, request):

        username = request.data.get('username')
        # 1是否为空
        if not username:
            return Response({'code': 20010})
        # 2是否符合
        name = re.match('\w{5,10}$', username)
        if not name:
            return Response({'code': 20011})
        # 3是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 20012})
            # 密码
        password = request.data.get('password')
        if not password:
            return Response({'code': 10010})
        password = re.match('\w{8,20}$', password)
        if not password:
            return Response({'code': 10011})

        # 手机号
        mobile = request.data.get('mobile')
        # 1是否为空
        if not mobile:
            return Response({'code': 20013})
        # 2是否符合
        num = re.match('^1[3-9]\d{9}$', mobile)
        if not num:
            return Response({'code': 20014})

        codes = request.data.get('codes')
        conn = get_redis()
        codess = conn.get(mobile)
        if codess:
            codess = str(codess, encoding='utf8')

        if codes == codess:
            request.data['password'] = make_password(request.data.get('password'))
            is_check = request.data.get('is_check')
            if is_check:
                ser = Userser(data=request.data)
                if ser.is_valid():
                    ser.save()
                    token = jwt.encode({'data': {'username': username}}, settings.SECRET_KEY, algorithm='HS256')
                    users = User.objects.filter(username=username).first()
                    return Response({'code': 200, 'token': token, 'userid': users.id})
                else:
                    print(ser.errors)
                    return Response({'code': 10016})

        return Response({'code': 200})


class NoteM(APIView):
    def post(self, request):
        # 手机号
        mobile = request.data.get('mobile')
        # uuid
        uid = request.data.get('uid')
        # 前端传过来的图形验证码
        imgcode = request.data.get('imgcode')
        # 1手机号是否为空
        if not mobile:
            return Response({'code': 20013})
        # 2是否符合
        num = re.match('^1[3-9]\d{9}$', mobile)
        if not num:
            return Response({'code': 20014})
        # 调用redis
        conn = get_redis()
        # 通过uuid获取存的验证码
        imgcodes = conn.get(uid)
        # 转换一下
        if imgcodes:
            imgcodes = str(imgcodes, encoding='utf8')
            # 判断前端传过来的和redis存的是否一样

            codes = random.randint(100000, 999999)
            res = send_message(mobile, str(codes), 1)
            code = 10010
            # 生成完以后 判断有没有东西，有的话保存一下短信验证码
            if res:
                code = 200
                coon = get_redis()
                coon.setex(mobile, 60, codes)
            return Response({'code': code})
        return Response({'code': 20010})


from utils.captcha.captcha import captcha


class CreatePic(APIView):
    def get(self, request):
        uuid = request.GET.get('uuid')
        name, text, pic = captcha.generate_captcha()
        # 保存再redis
        conn = get_redis()
        conn.set(uuid, text)
        return HttpResponse(pic, content_type='image/jpg')


from django.db.models import Q  # Q查询


# 登录
class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if user:
            if check_password(password, user.password):
                token = jwt.encode({'data': {'username': username, 'id': user.id}}, settings.SECRET_KEY,
                                   algorithm='HS256')
                return Response({'code': 200, 'token': token, 'userid': user.id})
            else:
                return Response({'code': 20010, 'mes': '密码错误'})
        else:
            return Response({'code': 20011, 'mes': '用户名不存在'})


from utils.comm import MAX_COMPILE


class ADDM(APIView):
    def post(self, request):
        userid = request.data.get('user')
        total = Address.objects.filter(user_id=userid).count()
        if total == MAX_COMPILE:
            return Response({'code': 30010, 'mes': '超过最大限制'})
        ser = AddSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        pid = request.GET.get('pid')
        if not pid:
            areas = Area.objects.filter(parent_id__isnull=True).all()
        else:
            areas = Area.objects.filter(parent_id=pid).all()
        ser = AreaSer(areas, many=True)
        return Response({'code': 200, 'list': ser.data})

    def put(self, request):
        # 获取要设置默认得ID
        id = request.GET.get('id')
        # 通过ID获取地址
        address = Address.objects.filter(id=id).first()
        # 把之前默认的地址改为普通的
        Address.objects.filter(user_id=address.user_id, is_default=1).update(is_default=0)
        # 把要操作的设置为默认
        address.is_default = 1
        # 保存
        address.save()
        return Response({'code': 200})


# 获取地址
class AddressM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if not id:
            userid = request.GET.get('userid')
            areas = Address.objects.filter(user_id=userid).all()
            ser = ShowAddSer(areas, many=True)
            total = Address.objects.filter(user_id=userid).count()
            return Response({'code': 200, 'list': ser.data, 'total': total, 'max_total': MAX_COMPILE})
        else:
            areas = Address.objects.filter(id=id).first()
            ser = ShowAddSer(areas)
            return Response({'code': 200, 'list': ser.data})

    def put(self, request):
        id = request.data.get('id')
        areas = Address.objects.filter(id=id).first()
        ser = AddSer(areas, request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 30012})
